package com.sfx.concurrent.demo.concurrent.ReentrantLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-01-09
 * Time: 16:30
 */
@Slf4j(topic = "c.LockInterruptiblyFeatures")
public class LockInterruptiblyFeatures {
    /**
     * 演示ReentrantLock可打断的特性
     */
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
            try {
                log.debug("尝试获取锁");
                lock.lockInterruptibly();
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.debug("没有获取到锁,被打断,返回");
                return;
            }
            try {
                log.debug("获取到锁");
            }finally {
                lock.unlock();
            }
        });
        log.debug("获取到锁");
        lock.lock();
        t1.start();
        try{
            log.debug("1s后打断t1");
            //主线程1s后打断t1线程
            Thread.sleep(1000);
            t1.interrupt();
        }finally {
            lock.unlock();
        }
    }
}
